package com.codi.bus.core.service.impl;

import com.codi.base.util.BigDecimalUtil;
import com.codi.base.util.DateUtils;
import com.codi.base.util.ExceptionUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.core.dao.ShareDetailDao;
import com.codi.bus.core.dao.UserDao;
import com.codi.bus.core.domain.ShareDetail;
import com.codi.bus.core.domain.User;
import com.codi.bus.core.resultModel.AssetsResult;
import com.codi.bus.core.service.util.HundsunUtils;
import com.codi.bus.core.util.ValueUtil;
import com.codi.bus.exception.SystemDBException;
import com.codi.fcloud.ufx.constant.HSOutputParameterNames;
import com.codi.trade.dto.ShareDetailQryDto;
import com.codi.trade.service.portfolio.HsShareDetailQryService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Transactional
public class LocaldataShareDetailService {

    private static final Logger logger = LoggerFactory.getLogger(LocaldataShareDetailService.class);
    @Autowired
    private UserDao userDao;
    @Autowired
    private HsShareDetailQryService hsShareDetailQryService;
    @Autowired
    private ShareDetailDao shareDetailDao;

    /**
     * 新增份额明细
     */
    public void addShareDetail(){
        try {
            //查询获取今天插入的数据
            List<ShareDetail> shareDetails = shareDetailDao.selectAllByAffirmDate(DateUtils.formatDate4(new Date()));
            List<String> allTaSerialId = new ArrayList<>();
            if(shareDetails != null && shareDetails.size() != 0){
                for (ShareDetail shareDetail : shareDetails) {
                    allTaSerialId.add(shareDetail.getTaSerialId());
                }
            }
            //获取所有用户
            List<User> users = userDao.getAllUser();
            for (User user : users) {
                AssetsResult result = new AssetsResult();
                 //判断是否已开户
                if (user == null || StringUtil.isEmpty(user.getExternalClientId())) {
                    continue;
                }
                //份额明细
                ShareDetailQryDto shareDetailQryDto = ShareDetailQryDto.builder()
                    .qry_beginrownum("1")
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .begin_date(DateUtils.formatDate4(new Date()))
                    .client_id(user.getExternalClientId())
                    .reqry_recordsum_flag("1")
                    .build();
                Map<String, Object> map = hsShareDetailQryService.query(shareDetailQryDto);
                List<Map<String, Object>> list = new ArrayList<>();
                HundsunUtils.ConvertToList(map, list, result);
                if (!result.getSuccess()) {
                    logger.error("新增份额明细addShareDetail数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                    return;
                }

                if(list == null || list.size()==0){
                    continue;
                }
                //查询今天是否已经插入过数据
//                List<ShareDetail> shareDetails = shareDetailDao.selectByClientIdAndAffirmDate(user.getExternalClientId(), DateUtils.formatDate4(new Date()));
                //插入
                excuteInsert(user,list,allTaSerialId);

                //返回的记录数有可能大于50  在这里进行判断 大于则多次循环查询
                if(StringUtil.isEmpty(list.get(0).get(HSOutputParameterNames.TOTAL_COUNT).toString())){
                        continue;
                }
                int totalCount = Integer.valueOf(list.get(0).get(HSOutputParameterNames.TOTAL_COUNT).toString());
                if(totalCount > 50){
                    if(totalCount % 50 != 0){
                        int count = totalCount/50 + 1;
                        for (int i = 1; i < count; i++) {
                            //直接从第2次循环开始
                            ShareDetailQryDto extra = ShareDetailQryDto.builder()
                                .qry_beginrownum(String.valueOf((50*i)+1))
                                .request_num(GlobalConstant.MAX_REQUEST_NUM)
                                .begin_date(DateUtils.formatDate4(new Date()))
                                .client_id(user.getExternalClientId())
                                .reqry_recordsum_flag("0")
                                .build();
                            Map<String, Object> extraMap = hsShareDetailQryService.query(extra);
                            List<Map<String, Object>> extraList = new ArrayList<>();
                            HundsunUtils.ConvertToList(extraMap, extraList, result);
                            if (!result.getSuccess()) {
                                logger.error("新增份额明细addShareDetail数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                                return;
                            }
                            if(extraList == null || extraList.size()==0){
                                logger.error("新增份额明细addShareDetail第"+(i+1)+"次查询失败，当前用户={}"+user.getUserId());
                                return;
                            }
                            //插入
                            excuteInsert(user,extraList,allTaSerialId);
                        }
                    }else{
                        int count = totalCount/50;
                        for (int i = 1; i < count; i++) {
                            //直接从第2次循环开始
                            ShareDetailQryDto extra = ShareDetailQryDto.builder()
                                .qry_beginrownum(String.valueOf((50*i)+1))
                                .request_num(GlobalConstant.MAX_REQUEST_NUM)
                                .begin_date(DateUtils.formatDate4(new Date()))
                                .client_id(user.getExternalClientId())
                                .reqry_recordsum_flag("0")
                                .build();
                            Map<String, Object> extraMap = hsShareDetailQryService.query(extra);
                            List<Map<String, Object>> extraList = new ArrayList<>();
                            HundsunUtils.ConvertToList(extraMap, extraList, result);
                            if (!result.getSuccess()) {
                                logger.error("新增份额明细addShareDetail数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                                return;
                            }
                            if(extraList == null || extraList.size()==0){
                                logger.error("新增份额明细addShareDetail第"+(i+1)+"次查询失败，当前用户={}",user.getUserId());
                                return;
                            }
                            //插入
                            excuteInsert(user,extraList,allTaSerialId);
                        }
                    }
                }

            }
        } catch (Exception e) {
            ExceptionUtil.logError(logger, "新增份额明细addShareDetail - Exception:", e);
            throw new SystemDBException("新增份额明细addShareDetail Failure!", e);
        }
    }

    /**
     * 初始化数据  需要给定日期
     */
    public void init(Date date){
        try {
            //查询获取全部数据
            List<ShareDetail> shareDetails = shareDetailDao.selectAll();
            List<String> allTaSerialId = new ArrayList<>();
            if(shareDetails != null && shareDetails.size() != 0){
                for (ShareDetail shareDetail : shareDetails) {
                    allTaSerialId.add(shareDetail.getTaSerialId());
                }
            }
            //获取所有用户
            List<User> users = userDao.getAllUser();

            for (User user : users) {
                AssetsResult result = new AssetsResult();

                // 判断是否已开户
                if (user == null || StringUtil.isEmpty(user.getExternalClientId())) {
                    continue;
                }
                //份额明细
                ShareDetailQryDto shareDetailQryDto = ShareDetailQryDto.builder()
                    .qry_beginrownum("1")
                    .request_num(GlobalConstant.MAX_REQUEST_NUM)
                    .reqry_recordsum_flag("1")
                    .client_id(user.getExternalClientId())
                    .end_date(DateUtils.formatDate4(date))  //设置指定日期为终止日期
                    .build();
                Map<String, Object> map = hsShareDetailQryService.query(shareDetailQryDto);
                List<Map<String, Object>> list = new ArrayList<>();
                HundsunUtils.ConvertToList(map, list, result);
                if (!result.getSuccess()) {
                    logger.error("份额明细init数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                    return;
                }
                if(list == null || list.size()==0){
                        continue;
                }
                //插入
                excuteInsert(user,list,allTaSerialId);

                //返回的记录数有可能大于50  在这里进行判断 大于则多次循环查询
                if(StringUtil.isEmpty(list.get(0).get(HSOutputParameterNames.TOTAL_COUNT).toString())){
                    continue;
                }
                int totalCount = Integer.valueOf(list.get(0).get(HSOutputParameterNames.TOTAL_COUNT).toString());
                if(totalCount > 50){
                    if(totalCount % 50 != 0){
                        int count = totalCount/50 + 1;
                        for (int i = 1; i < count; i++) {
                            //直接从第2次循环开始
                            ShareDetailQryDto extra = ShareDetailQryDto.builder()
                                .qry_beginrownum(String.valueOf((50*i)+1))
                                .request_num(GlobalConstant.MAX_REQUEST_NUM)
                                .end_date(DateUtils.formatDate4(date))  //设置指定日期为终止日期
                                .client_id(user.getExternalClientId())
                                .reqry_recordsum_flag("0")
                                .build();
                            Map<String, Object> extraMap = hsShareDetailQryService.query(extra);
                            List<Map<String, Object>> extraList = new ArrayList<>();
                            HundsunUtils.ConvertToList(extraMap, extraList, result);
                            if (!result.getSuccess()) {
                                logger.error("份额明细init数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                                return;
                            }
                            if(extraList == null || extraList.size()==0){
                                logger.error("份额明细init第"+(i+1)+"次查询失败，用户："+user.getUserId());
                                return;
                            }
                            //执行插入
                            excuteInsert(user,extraList,allTaSerialId);
                        }
                    }else{
                        int count = totalCount/50;
                        for (int i = 1; i < count; i++) {
                            //直接从第2次循环开始
                            ShareDetailQryDto extra = ShareDetailQryDto.builder()
                                .qry_beginrownum(String.valueOf((50*i)+1))
                                .request_num(GlobalConstant.MAX_REQUEST_NUM)
                                .end_date(DateUtils.formatDate4(date))  //设置指定日期为终止日期
                                .client_id(user.getExternalClientId())
                                .reqry_recordsum_flag("0")
                                .build();
                            Map<String, Object> extraMap = hsShareDetailQryService.query(extra);
                            List<Map<String, Object>> extraList = new ArrayList<>();
                            HundsunUtils.ConvertToList(extraMap, extraList, result);
                            if (!result.getSuccess()) {
                                logger.error("份额明细init数据错误：{},当前用户={}",result.getErrorMessage(),user.getUserId());
                                return;
                            }
                            if(extraList == null || extraList.size()==0){
                                logger.error("份额明细init第"+(i+1)+"次查询失败，用户："+user.getUserId());
                                return;
                            }
                            //插入
                            excuteInsert(user,extraList,allTaSerialId);
                        }
                    }
                }

            }
        } catch (Exception e) {
            ExceptionUtil.logError(logger, "份额明细init - Exception:", e);
            throw new SystemDBException("份额明细init Failure!", e);
        }

    }

    /**
     * 执行插入
     * @param user
     * @param list
     */
    public void excuteInsert(User user ,List<Map<String, Object>> list,List<String> allTaSerialId){
        for (Map<String, Object> item : list) {
            // 记录数
            String rowCount = ValueUtil.getObjStr(item.get(HSOutputParameterNames.ROWCOUNT));
            if (StringUtil.isEmpty(rowCount)) {
                return;
            }
            ShareDetail model = new ShareDetail();
            model.setUserId(user.getUserId().intValue());
            model.setClientId(user.getExternalClientId());
            model.setAffirmDate(ValueUtil.getObjStr(item.get(HSOutputParameterNames.AFFIRM_DATE)));
            model.setBusinessFrozenAmount(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(item.get(HSOutputParameterNames.BUSINESS_FROZEN_AMOUNT))));
            model.setEnableShares(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(item.get(HSOutputParameterNames.ENABLE_SHARES))));
            model.setFundBusinCode(ValueUtil.getObjStr(item.get(HSOutputParameterNames.FUND_BUSIN_CODE)));
            model.setFundCode(ValueUtil.getObjStr(item.get(HSOutputParameterNames.FUND_CODE)));
            model.setIncomeFloat(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(item.get(HSOutputParameterNames.INCOME_FLOAT))));
            model.setNetValue(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(item.get(HSOutputParameterNames.NET_VALUE))));
            model.setPortfolioCode(ValueUtil.getObjStr(item.get(HSOutputParameterNames.PORTFOLIO_CODE)));
            model.setRegDate(ValueUtil.getObjStr(item.get(HSOutputParameterNames.REG_DATE)));
            model.setShareexpireDate(ValueUtil.getObjStr(item.get(HSOutputParameterNames.SHAREEXPIRE_DATE)));
            model.setShareType(ValueUtil.getObjStr(item.get(HSOutputParameterNames.SHARE_TYPE)));
            model.setTaAcco(ValueUtil.getObjStr(item.get(HSOutputParameterNames.TA_ACCO)));
            model.setTaSerialId(ValueUtil.getObjStr(item.get(HSOutputParameterNames.TA_SERIAL_ID)));
            model.setTradeAcco(ValueUtil.getObjStr(item.get(HSOutputParameterNames.TRADE_ACCO)));
            model.setUnpaidIncome(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(item.get(HSOutputParameterNames.UNPAID_INCOME))));

            if(!allTaSerialId.contains(model.getTaSerialId())){
                shareDetailDao.insert(model);
            }
        }
    }

//    /**
//     * 执行新增插入
//     * @param user
//     * @param list
//     */
//    public void excuteAdd(User user,List<Map<String, Object>> list){
//        for (Map<String, Object> item : list) {
//            // 记录数
//            String rowCount = item.get(HSOutputParameterNames.ROWCOUNT).toString();
//            if (StringUtil.isEmpty(rowCount)) {
//                return;
//            }
////            if(shareDetails != null && shareDetails.size()!=0){
////                //验证是否插入过相同的数据  判断条件：交易账号、TA确认编号、基金代码
////                boolean flag = false;
////                for (ShareDetail shareDetail : shareDetails) {
////                    if(shareDetail.getFundCode().equals(item.get(HSOutputParameterNames.FUND_CODE).toString()) && shareDetail.getTradeAcco().equals(item.get(HSOutputParameterNames.TRADE_ACCO).toString()) && shareDetail.getTaSerialId().equals(item.get(HSOutputParameterNames.TA_SERIAL_ID).toString())){
////                        flag = true;
////                        break;
////                    }
////                }
////                if(flag){
////                    continue;
////                }
////            }
//            ShareDetail model = new ShareDetail();
//            model.setUserId(user.getUserId().intValue());
//            model.setClientId(user.getExternalClientId());
//            model.setAffirmDate(ValueUtil.getObjStr(HSOutputParameterNames.AFFIRM_DATE));
//            model.setBusinessFrozenAmount(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(HSOutputParameterNames.BUSINESS_FROZEN_AMOUNT)));
//            model.setEnableShares(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(HSOutputParameterNames.ENABLE_SHARES)));
//            model.setFundBusinCode(ValueUtil.getObjStr(HSOutputParameterNames.FUND_BUSIN_CODE));
//            model.setFundCode(ValueUtil.getObjStr(HSOutputParameterNames.FUND_CODE));
//            model.setIncomeFloat(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(HSOutputParameterNames.INCOME_FLOAT)));
//            model.setNetValue(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(HSOutputParameterNames.NET_VALUE)));
//            model.setPortfolioCode(ValueUtil.getObjStr(HSOutputParameterNames.PORTFOLIO_CODE));
//            model.setRegDate(ValueUtil.getObjStr(HSOutputParameterNames.REG_DATE));
//            model.setShareexpireDate(ValueUtil.getObjStr(HSOutputParameterNames.SHAREEXPIRE_DATE));
//            model.setShareType(ValueUtil.getObjStr(HSOutputParameterNames.SHARE_TYPE));
//            model.setTaAcco(ValueUtil.getObjStr(HSOutputParameterNames.TA_ACCO));
//            model.setTaSerialId(ValueUtil.getObjStr(HSOutputParameterNames.TA_SERIAL_ID));
//            model.setTradeAcco(ValueUtil.getObjStr(HSOutputParameterNames.TRADE_ACCO));
//            model.setUnpaidIncome(BigDecimalUtil.ConvertToBigDecimal(ValueUtil.getObjStr(HSOutputParameterNames.UNPAID_INCOME)));
//
//            ShareDetail shareDetail = shareDetailDao.selectByTaSerialId(model.getTaSerialId());
//            if(shareDetail == null){
//                shareDetailDao.insert(model);
//            }
//        }
//    }
}
